package com.foreknow.test;

import com.foreknow.model.Admin;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 使用的库为json-lib
 * 作用:
 * 1.可以将bean转换为字符串
 * 2.也可以将字符串转换为bean
 */
public class JSONArrayDemo {
    public static void main(String[] args) {
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(0,"tom1");
        jsonArray.add(1,"tom2");
        jsonArray.element("text 123");
        System.out.println(jsonArray);
        System.out.println(jsonArray.get(0));

        System.out.println("-+-----------------------------");
        //JSONObject :JSON字符串对象形式
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username","tom123");
        jsonObject.put("password","123");
        jsonArray.add(jsonObject);
        System.out.println(jsonArray);

        //可以使用json-lib库将list集合转换为json串
        Admin admin= new Admin();
        Admin admin1= new Admin();
        admin.setId(1);
        admin.setUsername("tom");
        admin.setPassword("123");
        admin1.setId(2);
        admin1.setUsername("tom2");
        admin1.setPassword("1232");

        List<Admin> list = new ArrayList<Admin>();
        list.add(admin);
        list.add(admin1);
        JSONArray json = JSONArray.fromObject(list);
        System.out.println(json.toString());

        Map<String ,Object> map = new HashMap<>();
        map.put("1",admin);
        map.put("2",admin1);
        JSONObject jsonObject1  =JSONObject.fromObject(map);
        System.out.println(jsonObject1.toString());

    }
}

















